package api

import (
	"blog/library"
	"blog/models"
	"github.com/astaxie/beego/orm"
)

type AdminController struct {
	baseController
}

func (a *AdminController) List() {
	page, _ := a.GetInt("page", 1)
	limit, _ := a.GetInt("limit", 25)
	list, total, _ := models.GetList(models.AdminTable(), page, limit, &orm.Condition{}, "-Id")
	a.success(list, "", total)
}

func (a *AdminController) Create() {
	admin := models.NewAdmin()
	admin.Account = a.GetString("account")
	password := library.RandString(8)
	admin.Password = library.Md5(password)
	admin.Avatar = a.GetString("avatar")
	admin.Email = a.GetString("email")
	admin.Nickname = a.GetString("nickname")
	if _, err := models.Create(admin); err != nil {
		a.error(err.Error())
	}
	a.success(password)
}

func (a *AdminController) Edit() {
	id, _ := a.GetInt("id", -1)
	if id == -1 {
		a.error("id错误")
	}
	admin := new(models.Admin)
	admin.Id = id
	admin.Avatar = a.GetString("avatar")
	admin.Email = a.GetString("email")
	admin.Nickname = a.GetString("nickname")
	if _, err := models.UpdateByCondition(admin); err != nil {
		a.error(err.Error())
	}
	a.success(id)
}

func (a *AdminController) ChangePassword() {
	id, _ := a.GetInt("id")
	newPassword := a.GetString("new_password")
	rePassword := a.GetString("re_password")
	if newPassword != rePassword {
		a.error("两次密码不一致")
	}
	adminStruct := new(models.Admin)
	adminStruct.Id = id
	adminStruct.Password = library.Md5(newPassword)
	rows, err := models.UpdateByCondition(adminStruct)
	if err != nil {
		a.error(err.Error())
	}
	a.success(rows)
}

func (a *AdminController) ChangeRole() {

}
